package cn.snow.iot.module.cps.controller.admin.product;

import cn.hutool.core.bean.BeanUtil;

import cn.snow.iot.framework.common.pojo.CommonResult;
import cn.snow.iot.module.cps.controller.admin.product.vo.ProductPage;
import cn.snow.iot.module.cps.controller.admin.product.vo.ProductPageVO;
import cn.snow.iot.module.cps.dal.dataobject.product.ProductDO;
import cn.snow.iot.module.cps.service.product.ProductService;
import cn.snow.iot.module.cps.utils.StringToList;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Tag(name = "管理后台 - 产品管理")
@RestController
@RequestMapping("/cps/product")
public class ProductController {

    @Resource
    private ProductService productService;

    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "详情")
    public CommonResult<ProductDO> detail (Long id) {
        return CommonResult.success(productService.getById(id));
    }

    /**
     * 查询自定义分页
     * @return
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 2)
    public CommonResult<IPage<ProductPage>> page(ProductPageVO pageVO) {
        IPage<ProductPage> pages = productService.selectProductPage(pageVO);
        return CommonResult.success(pages);
    }

    /**
     * 新增或修改
     * @param productDo
     * @return
     */
    @PostMapping("submit")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "新增或修改")
    public CommonResult<ProductDO> submit(@RequestBody ProductDO productDo) {
        if(productDo.getId() == null && productDo.getProductCode() != null) {
            ProductDO product = productService.lambdaQuery().eq(ProductDO::getProductCode, productDo.getProductCode()).one();
            if (!(BeanUtil.isEmpty(product))) {
                return CommonResult.error(207, "产品编码已存在");
            }
        }
        productService.saveOrUpdate(productDo);
        return CommonResult.success(productDo);
    }

    /**
     * 逻辑删除
     * @param ids
     * @return
     */
    @GetMapping("/remove")
    @ApiOperationSupport(order = 4)
    public CommonResult<Boolean> remove(@RequestParam String ids) {
        return CommonResult.success(productService.removeProduct(StringToList.toLongList(ids)));
    }
}
